#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
可视化面板模块
处理Petri网的显示和交互
"""

from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QGraphicsView,
                           QPushButton, QLabel, QGraphicsScene)
from PyQt5.QtCore import Qt, pyqtSignal
from PyQt5.QtGui import QPainter

class PetriNetGraphicsView(QGraphicsView):
    """Petri网图形视图类，支持缩放和平移"""
    
    def __init__(self, parent=None):
        """初始化图形视图"""
        super().__init__(parent)
        self.setRenderHint(QPainter.Antialiasing)  # 抗锯齿
        self.setRenderHint(QPainter.SmoothPixmapTransform)  # 平滑缩放
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.setTransformationAnchor(QGraphicsView.AnchorUnderMouse)
        self.setResizeAnchor(QGraphicsView.AnchorUnderMouse)
        self.setViewportUpdateMode(QGraphicsView.FullViewportUpdate)
        self.scale_factor = 1.0
        
    def wheelEvent(self, event):
        """处理鼠标滚轮事件"""
        if event.modifiers() & Qt.ControlModifier:
            # 计算缩放因子
            factor = 1.1 if event.angleDelta().y() > 0 else 0.9
            self.scale(factor, factor)
            self.scale_factor *= factor
        else:
            super().wheelEvent(event)
    
    def mousePressEvent(self, event):
        """处理鼠标按下事件"""
        if event.button() == Qt.MiddleButton:
            self.setDragMode(QGraphicsView.ScrollHandDrag)
            event = type(event)(event.type(), event.pos(), Qt.LeftButton, 
                              event.buttons() | Qt.LeftButton, event.modifiers())
        super().mousePressEvent(event)
    
    def mouseReleaseEvent(self, event):
        """处理鼠标释放事件"""
        if event.button() == Qt.MiddleButton:
            self.setDragMode(QGraphicsView.NoDrag)
            event = type(event)(event.type(), event.pos(), Qt.LeftButton, 
                              event.buttons() & ~Qt.LeftButton, event.modifiers())
        super().mouseReleaseEvent(event)
    
    def reset_view(self):
        """重置视图"""
        self.resetTransform()
        self.scale_factor = 1.0
        if self.scene():
            self.fitInView(self.scene().sceneRect(), Qt.KeepAspectRatio)

class VisualizationPanel(QWidget):
    """可视化面板类，显示Petri网和控制按钮"""
    
    def __init__(self, parent=None):
        """初始化可视化面板"""
        super().__init__(parent)
        self.scene = None
        self._init_ui()
    
    def _init_ui(self):
        """初始化UI组件"""
        # 创建布局
        layout = QVBoxLayout(self)
        
        # 创建工具栏
        toolbar = QHBoxLayout()
        
        # 添加缩放按钮
        zoom_in_btn = QPushButton("放大")
        zoom_out_btn = QPushButton("缩小")
        fit_view_btn = QPushButton("适应视图")
        reset_view_btn = QPushButton("重置缩放")
        
        toolbar.addWidget(zoom_in_btn)
        toolbar.addWidget(zoom_out_btn)
        toolbar.addWidget(fit_view_btn)
        toolbar.addWidget(reset_view_btn)
        toolbar.addStretch()
        
        # 创建图形视图
        self.graphics_view = PetriNetGraphicsView()
        
        # 创建状态标签
        self.status_label = QLabel("就绪")
        
        # 添加到主布局
        layout.addLayout(toolbar)
        layout.addWidget(self.graphics_view)
        layout.addWidget(self.status_label)
        
        # 连接信号
        zoom_in_btn.clicked.connect(self._zoom_in)
        zoom_out_btn.clicked.connect(self._zoom_out)
        fit_view_btn.clicked.connect(self._fit_view)
        reset_view_btn.clicked.connect(self._reset_view)
        
        # 设置初始状态
        self.show_welcome_message()
    
    def _zoom_in(self):
        """放大视图"""
        self.graphics_view.scale(1.2, 1.2)
        self.graphics_view.scale_factor *= 1.2
        self._update_status()
    
    def _zoom_out(self):
        """缩小视图"""
        self.graphics_view.scale(0.8, 0.8)
        self.graphics_view.scale_factor *= 0.8
        self._update_status()
    
    def _fit_view(self):
        """适应视图"""
        if self.scene:
            self.graphics_view.fitInView(self.scene.sceneRect(), Qt.KeepAspectRatio)
            self._update_status()
    
    def _reset_view(self):
        """重置视图"""
        self.graphics_view.reset_view()
        self._update_status()
    
    def _update_status(self):
        """更新状态标签"""
        scale = int(self.graphics_view.scale_factor * 100)
        self.status_label.setText(f"缩放: {scale}%")
    
    def show_welcome_message(self):
        """显示欢迎信息"""
        scene = QGraphicsScene()
        scene.addText("欢迎使用过程挖掘分析工具\n\n"
                     "请导入日志文件并选择挖掘算法开始分析")
        self.graphics_view.setScene(scene)
        self.graphics_view.fitInView(scene.sceneRect(), Qt.KeepAspectRatio)
    
    def show_error(self, message):
        """显示错误信息
        
        Args:
            message: 错误信息
        """
        scene = QGraphicsScene()
        scene.addText(f"错误：{message}")
        self.graphics_view.setScene(scene)
        self.graphics_view.fitInView(scene.sceneRect(), Qt.KeepAspectRatio)
    
    def resizeEvent(self, event):
        """处理调整大小事件"""
        super().resizeEvent(event)
        if self.scene:
            self.graphics_view.fitInView(self.scene.sceneRect(), Qt.KeepAspectRatio)
            self._update_status() 